import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import jwt from 'jsonwebtoken';
import User from './models/user.js';
import pool from './config/db.js';
import nodemailer from 'nodemailer';
import crypto from 'crypto';
import Product from './models/product.js';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import Order from './models/order.js';
import multer from 'multer';
import Address from './models/address.js';
import { imageCache } from './middleware/imageCache.js'
import { sendMail, testEmailConnection } from './config/mail.js';
import aiService from './services/aiService.js'
import sharp from 'sharp';
import debugRoutes from './routes/debugRoutes.js';
import aiRoutes from './routes/aiRoutes.js';
import cartRoutes from './routes/cart.js';
import addressRoutes from './routes/address.js';
import orderRouter from './routes/order.js';
import paymentRouter from './routes/payment.js';
import storyRoutes from './routes/storyRoutes.js';
import userRoutes from './routes/userRoutes.js';
import adminRoutes from './routes/adminRoutes.js';
import { swaggerSetup } from './config/swagger.js';

// 加载环境变量
dotenv.config();

const app = express();

// 获取 __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 确保上传目录存在
const uploadsDir = path.join(__dirname, '../../uploads');
const bannersDir = path.join(uploadsDir, 'banners');
const productsDir = path.join(uploadsDir, 'products');

[uploadsDir, bannersDir, productsDir].forEach(dir => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
});

// 基础中间件配置
app.use(cors({
  origin: ['http://localhost:5173', 'http://localhost:5000','https://servicewechat.com'],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(express.json());

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`, {
    query: req.query,
    body: req.method !== 'GET' ? req.body : undefined
  });
  next();
});

// 静态文件服务
// 注意: 上传文件存储在项目根目录下的uploads文件夹中，而不是server目录下
const uploadsPath = path.join(__dirname, '../../uploads');
app.use('/uploads', express.static(uploadsPath));
console.log('静态文件目录配置:', { 
  uploadsPath,
  exists: fs.existsSync(uploadsPath)
});

// 添加公共静态文件目录，用于提供测试页面
// 修正路径问题，确保public文件夹可以被正确访问
app.use(express.static(path.join(__dirname, '../public')));
// 添加额外的调试日志
console.log('静态文件目录路径:', path.join(__dirname, '../public'));
console.log('当前工作目录:', process.cwd());

// 添加图片缓存中间件
app.use('/uploads', imageCache)

// 在API路由之前加载Swagger文档
console.log('正在加载Swagger文档...');
swaggerSetup(app);

// 添加文档测试端点
app.get('/docs', (req, res) => {
  console.log('访问文档重定向页面');
  res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>API文档</title>
        <meta http-equiv="refresh" content="0;url=/inline-swagger.html">
        <style>
          body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
        </style>
      </head>
      <body>
        <h1>正在跳转到API文档...</h1>
        <p>如果没有自动跳转，请点击以下链接：</p>
        <p>
          <a href="/api-docs">标准文档</a> | 
          <a href="/inline-swagger.html">内联文档</a> | 
          <a href="/swagger-test.html">测试页面</a>
        </p>
      </body>
    </html>
  `);
});

// 添加一个专门针对swagger的测试端点
app.get('/api/swagger-test', (req, res) => {
  res.json({
    status: 'success',
    message: 'Swagger API测试成功',
    availableEndpoints: [
      '/api-docs',
      '/api-docs-ui',
      '/api-docs-json',
      '/api-docs-test',
      '/inline-swagger.html',
      '/swagger-test.html',
      '/docs'
    ]
  });
});

// 获取新品列表 - 移到这里
app.get('/api/products/new', async (req, res) => {
  try {
    console.log('Received request for new products:', req.query);
    
    const { 
      page = 1, 
      limit = 12, 
      sort = 'newest',
      minPrice,
      maxPrice,
      categories
    } = req.query;

    const result = await Product.getNewProducts({
      page: parseInt(page),
      limit: parseInt(limit),
      sort,
      minPrice: minPrice ? parseFloat(minPrice) : null,
      maxPrice: maxPrice ? parseFloat(maxPrice) : null,
      categories: categories ? categories.split(',') : null
    });

    console.log('Sending response:', result);
    res.json(result);
  } catch (error) {
    console.error('Error in GET /api/products/new:', error);
    res.status(500).json({ 
      message: '获取新品列表失败',
      error: error.message 
    });
  }
});

// 获取热门商品
app.get('/api/products/hot', async (req, res) => {
  try {
    console.log('Received hot products request');
    const { limit = 8 } = req.query;
    
    // 验证 limit 参数
    const parsedLimit = Number(limit);
    if (isNaN(parsedLimit) || parsedLimit < 1) {
      return res.status(400).json({
        success: false,
        message: '无效的 limit 参数',
        data: []
      });
    }

    const hotProducts = await Product.getHotProducts(parsedLimit);
    console.log('Hot products response:', hotProducts);

    // 确保返回的数据格式正确
    res.json({
      success: true,
      message: '获取热门商品成功',
      data: Array.isArray(hotProducts) ? hotProducts : []
    });
  } catch (error) {
    console.error('Error fetching hot products:', error);
    res.status(500).json({
      success: false,
      message: '获取热门商品失败',
      data: []
    });
  }
});

// 添加测试路由来验证图片访问
app.get('/test-image', (req, res) => {
  res.send(`
    <h1>测试图片访问</h1>
    <img src="/uploads/banners/banner1.png" alt="Banner 1" />
    <img src="/uploads/banners/banner2.png" alt="Banner 2" />
    <img src="/uploads/banners/banner3.png" alt="Banner 3" />
  `);
});

// 初始化数据库
const initializeDatabase = async () => {
  try {
    // 检查是否存在管理员用户
    const adminUser = await User.findByUsername('admin');
    if (!adminUser) {
      // 创建管理员用户
      await User.create({
        username: 'admin',
        password: '123456',
        email: 'admin@example.com'
      });
      console.log('Admin user created successfully');
    }
  } catch (error) {
    console.error('Database initialization error:', error);
  }
};

// 启动时初始化数据库
initializeDatabase();

// 创建邮件发送器
const transporter = nodemailer.createTransport({
  host: process.env.MAIL_HOST,
  port: process.env.MAIL_PORT,
  secure: false, // 改为 false，因为使用 587 端口
  auth: {
    user: process.env.MAIL_USER,
    pass: process.env.MAIL_PASS
  },
  tls: {
    // 修改 TLS 配置
    ciphers: 'SSLv3',
    rejectUnauthorized: false // 开发环境可以设置为 false
  }
});

// 验证邮件配置
transporter.verify(function(error, success) {
  if (error) {
    console.error('邮件服务器配置错误:', error);
  } else {
    console.log('邮件服务器配置成功');
  }
});

// 登录路由
app.post('/api/auth/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    // 添加日志
    console.log('Login attempt:', { username });
    
    // 验证必填字段
    if (!username || !password) {
      return res.status(400).json({ 
        success: false,
        message: '用户名和密码都是必填的' 
      });
    }

    // 验证用户
    const result = await User.authenticate(username, password);
    if (!result) {
      console.log('Authentication failed for user:', username);
      return res.status(401).json({ 
        success: false,
        message: '用户名或密码错误' 
      });
    }

    console.log('Login successful for user:', username);
    
    // 返回成功响应
    res.json({
      success: true,
      data: {
        token: result.token,
        user: result.user
      }
    });
  } catch (error) {
    console.error('Login error:', error);
    res.status(500).json({ 
      success: false,
      message: error.message || '服务器错误，请稍后重试' 
    });
  }
});

// 注册路由
app.post('/api/auth/register', async (req, res) => {
  try {
    const { username, email, password } = req.body;
    
    // 验证必填字段
    if (!username || !email || !password) {
      return res.status(400).json({ message: '所有字段都是必填的' });
    }
    
    // 检查用户名是否已存在
    const existingUser = await User.findByUsername(username);
    if (existingUser) {
      return res.status(400).json({ message: '用户名已被使用' });
    }
    
    // 检查邮箱是否已存在
    const existingEmail = await User.findByEmail(email);
    if (existingEmail) {
      return res.status(400).json({ message: '邮箱已被使用' });
    }
    
    // 创建新用户
    const userId = await User.create({
      username,
      email,
      password
    });
    
    res.status(201).json({ message: '注册成功' });
  } catch (error) {
    console.error('Registration error:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 发送重置密码邮件的路由
app.post('/api/auth/forgot-password', async (req, res) => {
  try {
    const { email } = req.body;
    const user = await User.findByEmail(email);
    
    if (!user) {
      return res.status(404).json({ message: '该邮箱未注册' });
    }

    const token = crypto.randomBytes(32).toString('hex');
    const expiry = new Date(Date.now() + 24 * 60 * 60 * 1000);
    
    await User.saveResetToken(user.id, token, expiry);

    const resetLink = `${process.env.FRONTEND_URL}/reset-password/${token}`;
    
    await sendMail({
      to: email,
      subject: '重置您的密码 - StoryPlush',
      html: `
        <div style="max-width: 600px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif;">
          <h2 style="color: #333; text-align: center;">重置您的密码</h2>
          <p>尊敬的用户：</p>
          <p>我们收到了您的密码重置请求。请点击下面的按钮重置密码：</p>
          <div style="text-align: center; margin: 30px 0;">
            <a href="${resetLink}" 
               style="background-color: #409EFF; color: white; padding: 12px 24px; 
                      text-decoration: none; border-radius: 4px; display: inline-block;">
              重置密码
            </a>
          </div>
          <p>如果按钮无法点击，请复制以下链接到浏览器地址栏：</p>
          <p style="background: #f5f5f5; padding: 10px; word-break: break-all;">
            ${resetLink}
          </p>
          <p>此链接将在24小时后过期。</p>
          <p>如果您没有请求重置密码，请忽略此邮件。</p>
          <hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
          <p style="color: #666; font-size: 12px; text-align: center;">
            这是一封系统自动发送的邮件，请勿直接回复。
          </p>
        </div>
      `
    });

    res.json({ message: '重置链接已发送到您的邮箱' });
  } catch (error) {
    console.error('Forgot password error:', error);
    res.status(500).json({ message: '发送重置邮件失败' });
  }
});

// 验证重置token
app.get('/api/auth/verify-reset-token/:token', async (req, res) => {
  try {
    const { token } = req.params;
    const isValid = await User.verifyResetToken(token);
    
    if (!isValid) {
      return res.status(400).json({ message: '重置链接无效或已过期' });
    }
    
    res.json({ message: 'Token有效' });
  } catch (error) {
    console.error('Verify reset token error:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 重置密码
app.post('/api/auth/reset-password', async (req, res) => {
  try {
    const { token, password } = req.body;
    
    // 验证token并更新密码
    const user = await User.resetPassword(token, password);
    if (!user) {
      return res.status(400).json({ message: '重置链接无效或已过期' });
    }
    
    res.json({ message: '密码重置成功' });
  } catch (error) {
    console.error('Reset password error:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取首页数据
app.get('/api/home', async (req, res) => {
  try {
    // 并行获取所有数据
    const [hotProducts, activeTheme] = await Promise.all([
      Product.getHotProducts(8),
      Product.getActiveTheme()
    ]);

    // 如果有活动主题，获取主题商品
    let themeProducts = [];
    if (activeTheme) {
      themeProducts = await Product.getThemeProducts(activeTheme.id);
    }

    // 处理主题图片路径
    const theme = activeTheme ? {
      ...activeTheme,
      image: activeTheme.image && !activeTheme.image.startsWith('http')
        ? `/uploads/${activeTheme.image}`
        : activeTheme.image
    } : null;

    res.json({
      hotProducts: hotProducts || [],
      theme: theme ? {
        ...theme,
        products: themeProducts
      } : null
    });
  } catch (error) {
    console.error('Error fetching home data:', error);
    res.status(500).json({
      message: '获取数据失败',
      hotProducts: [],
      theme: null
    });
  }
});

// 测试路由
app.get('/api/test', (req, res) => {
  res.json({ message: 'API is working' });
});

// 添加调试路由
app.get('/api/debug/images', (req, res) => {
  const fs = require('fs');
  const path = require('path');
  
  const uploadsDir = path.join(__dirname, '../../uploads');
  
  const scanDir = (dir) => {
    const results = [];
    const items = fs.readdirSync(dir);
    
    items.forEach(item => {
      const fullPath = path.join(dir, item);
      const stat = fs.statSync(fullPath);
      
      if (stat.isDirectory()) {
        results.push(...scanDir(fullPath));
      } else {
        results.push({
          path: fullPath.replace(uploadsDir, ''),
          size: stat.size,
          permissions: stat.mode.toString(8)
        });
      }
    });
    
    return results;
  };
  
  try {
    const images = scanDir(uploadsDir);
    res.json({
      uploadsPath: uploadsDir,
      images: images
    });
  } catch (error) {
    res.status(500).json({
      error: error.message,
      stack: error.stack
    });
  }
});

// 添加图片测试路由
app.get('/api/test-images', (req, res) => {
  const fs = require('fs').promises;
  const path = require('path');
  
  const uploadsDir = path.join(__dirname, '../../uploads');
  
  async function checkImages() {
    try {
      const stats = {
        uploadsPath: uploadsDir,
        exists: await fs.access(uploadsDir).then(() => true).catch(() => false),
        permissions: null,
        contents: null
      };
      
      if (stats.exists) {
        const stat = await fs.stat(uploadsDir);
        stats.permissions = stat.mode.toString(8);
        stats.contents = await fs.readdir(uploadsDir, { withFileTypes: true });
      }
      
      return stats;
    } catch (error) {
      return { error: error.message };
    }
  }
  
  checkImages().then(stats => res.json(stats));
});

// 添加文件检查路由
app.get('/api/check-files', (req, res) => {
  try {
    const uploadsDir = path.join(__dirname, '../../uploads');
    const files = {
      products: [],
      banners: []
    };
    
    // 检查 products 目录
    const productsDir = path.join(uploadsDir, 'products');
    if (fs.existsSync(productsDir)) {
      files.products = fs.readdirSync(productsDir);
    }
    
    // 检查 banners 目录
    const bannersDir = path.join(uploadsDir, 'banners');
    if (fs.existsSync(bannersDir)) {
      files.banners = fs.readdirSync(bannersDir);
    }
    
    // 添加更多调试信息
    const response = {
      success: true,
      uploadsPath: uploadsDir,
      exists: {
        uploadsDir: fs.existsSync(uploadsDir),
        productsDir: fs.existsSync(productsDir),
        bannersDir: fs.existsSync(bannersDir)
      },
      files: files
    };

    console.log('Files check response:', response);
    res.json(response);
  } catch (error) {
    console.error('Files check error:', error);
    res.status(500).json({
      success: false,
      error: error.message,
      stack: error.stack
    });
  }
});

// 获取商品详情
app.get('/api/products/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const product = await Product.getProductById(id);
    
    if (!product) {
      return res.status(404).json({ message: '商品不存在' });
    }

    // 处理图片路径
    if (product.image && !product.image.startsWith('http')) {
      product.image = `${req.protocol}://${req.get('host')}/uploads/${product.image}`;
    }
    
    res.json(product);
  } catch (error) {
    console.error('Error fetching product:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 生成商品故事
app.post('/api/products/:id/story', async (req, res) => {
  try {
    const { id } = req.params;
    const product = await Product.getProductById(id);
    
    if (!product) {
      return res.status(404).json({ message: '商品不存在' });
    }

    const story = await Product.generateStory(product.name, product.description);
    res.json(story);
  } catch (error) {
    console.error('Error generating story:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取商品评论
app.get('/api/products/:id/reviews', async (req, res) => {
  try {
    const { id } = req.params;
    const reviews = await Product.getProductReviews(id);
    res.json(reviews);
  } catch (error) {
    console.error('Error fetching reviews:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 创建商品评论
app.post('/api/products/:id/reviews', async (req, res) => {
  try {
    const { id } = req.params;
    const { title, content, rating } = req.body;
    
    // 这里应该从 token 中获取用户 ID，暂时使用模拟数据
    const userId = 1; // 模拟已登录用户
    
    await Product.createReview(id, userId, { title, content, rating });
    res.json({ message: '评论发布成功' });
  } catch (error) {
    console.error('Error creating review:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 添加认证中间件
const authenticateToken = (req, res, next) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    // 添加调试日志
    console.log('Auth header:', authHeader);
    console.log('Token:', token);

    if (!token) {
      return res.status(401).json({ 
        success: false,
        message: '未登录' 
      });
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key');
    console.log('Decoded token:', decoded);

    req.user = {
      id: decoded.id, // 修改这里，之前是 userId
      username: decoded.username
    };
    next();
  } catch (error) {
    console.error('Token verification error:', error);
    return res.status(403).json({ 
      success: false,
      message: '无效的token' 
    });
  }
};

// 获取心愿单
app.get('/api/wishlist', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const wishlist = await User.getWishlist(userId);
    
    // 处理图片路径
    const processedWishlist = wishlist.map(item => {
      if (item.image && !item.image.startsWith('http')) {
        return {
          ...item,
          image: `${req.protocol}://${req.get('host')}/uploads/${item.image}`
        };
      }
      return item;
    });
    
    res.json(processedWishlist);
  } catch (error) {
    console.error('Error in GET /api/wishlist:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 添加到心愿单
app.post('/api/wishlist/:productId', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const productId = parseInt(req.params.productId);

    // 验证产品是否存在
    const [product] = await pool.query('SELECT id FROM products WHERE id = ?', [productId]);
    if (!product.length) {
      return res.status(404).json({ message: '产品不存在' });
    }

    // 检查是否已经在心愿单中
    const [existing] = await pool.query(
      'SELECT id FROM wishlist WHERE user_id = ? AND product_id = ?',
      [userId, productId]
    );

    if (existing.length > 0) {
      return res.status(400).json({ message: '该商品已在心愿单中' });
    }

    // 添加到心愿单
    await pool.query(
      'INSERT INTO wishlist (user_id, product_id) VALUES (?, ?)',
      [userId, productId]
    );

    res.status(201).json({ message: '添加成功' });
  } catch (error) {
    console.error('Error in POST /api/wishlist:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 从心愿单移除
app.delete('/api/wishlist/:productId', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const productId = parseInt(req.params.productId);

    const [result] = await pool.query(
      'DELETE FROM wishlist WHERE user_id = ? AND product_id = ?',
      [userId, productId]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '商品不在心愿单中' });
    }

    res.json({ message: '移除成功' });
  } catch (error) {
    console.error('Error in DELETE /api/wishlist:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取购物车
app.get('/api/cart', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const cart = await User.getCart(userId);
    
    // 处理图片路径
    const processedCart = cart.map(item => ({
      ...item,
      image: item.image && !item.image.startsWith('http')
        ? `${req.protocol}://${req.get('host')}/uploads/${item.image}`
        : item.image
    }));
    
    res.json(processedCart);
  } catch (error) {
    console.error('Error in GET /api/cart:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 添加到购物车
app.post('/api/cart', authenticateToken, async (req, res) => {
  try {
    const { productId, quantity } = req.body;
    const userId = req.user.id;
    
    await User.addToCart(userId, productId, quantity);
    res.json({ message: '添加成功' });
  } catch (error) {
    console.error('Error in POST /api/cart:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新购物车商品数量
app.put('/api/cart/:itemId', authenticateToken, async (req, res) => {
  try {
    const { itemId } = req.params;
    const { quantity } = req.body;
    const userId = req.user.id;
    
    await User.updateCartItemQuantity(userId, itemId, quantity);
    res.json({ message: '更新成功' });
  } catch (error) {
    console.error('Error in PUT /api/cart:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除购物车商品
app.delete('/api/cart/:itemId', authenticateToken, async (req, res) => {
  try {
    const { itemId } = req.params;
    const userId = req.user.id;
    
    await User.removeFromCart(userId, itemId);
    res.json({ message: '删除成功' });
  } catch (error) {
    console.error('Error in DELETE /api/cart:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取购物车数量
app.get('/api/cart/count', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const count = await User.getCartCount(userId);
    res.json({ count });
  } catch (error) {
    console.error('Error in GET /api/cart/count:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取心愿单数量
app.get('/api/wishlist/count', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const count = await User.getWishlistCount(userId);
    res.json({ count });
  } catch (error) {
    console.error('Error in GET /api/wishlist/count:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取用户个人资料
app.get('/api/user/profile', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const profile = await User.getProfile(userId);
    
    res.json({
      success: true,
      data: profile
    });
  } catch (error) {
    console.error('Error getting profile:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取个人资料失败'
    });
  }
});

// 更新用户信息
app.put('/api/user/profile', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { username, email } = req.body;
    
    // 验证数据
    if (!username || !email) {
      throw new Error('用户名和邮箱不能为空');
    }
    
    // 更新用户信息
    await User.updateProfile(userId, { username, email });
    
    // 获取更新后的用户信息
    const updatedUser = await User.getProfile(userId);
    
    res.json({
      message: '更新成功',
      user: updatedUser
    });
  } catch (error) {
    console.error('Error in update profile:', error);
    res.status(400).json({ message: error.message });
  }
});

// 获取订单列表
app.get('/api/orders', authenticateToken, async (req, res) => {
  try {
    const { status } = req.query;
    if (!req.user || !req.user.id) {
      return res.status(401).json({ message: '未授权访问' });
    }

    const result = await Order.getOrders(req.user.id, { status });
    res.json(result);
  } catch (error) {
    console.error('Error in GET /api/orders:', error);
    res.status(500).json({ 
      message: '获取订单列表失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
});

// 获取最近订单
app.get('/api/orders/recent', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const orders = await Order.getRecentOrders(userId);
    res.json(orders);
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 确认收货
app.post('/api/orders/:id/confirm', authenticateToken, async (req, res) => {
  try {
    await Order.confirmReceive(req.user.id, req.params.id);
    res.json({ message: '确认收货成功' });
  } catch (error) {
    console.error('Error in POST /api/orders/confirm:', error);
    res.status(500).json({ message: '操作失败' });
  }
});

// 取消订单
app.post('/api/orders/:id/cancel', authenticateToken, async (req, res) => {
  try {
    await Order.cancelOrder(req.user.id, req.params.id);
    res.json({ message: '订单已取消' });
  } catch (error) {
    console.error('Error in POST /api/orders/cancel:', error);
    res.status(500).json({ message: '操作失败' });
  }
});

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const avatarPath = path.join(__dirname, '../../uploads/avatars');
    // 确保目录存在
    if (!fs.existsSync(avatarPath)) {
      fs.mkdirSync(avatarPath, { recursive: true });
    }
    cb(null, avatarPath);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, 'avatar-' + uniqueSuffix + ext);
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024 // 限制5MB
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('不支持的文件类型'));
    }
  }
});

// 上传头像 - 简化版本，不使用 Sharp
app.post('/api/user/avatar', authenticateToken, upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ message: '没有上传文件' });
    }

    const userId = req.user.id;
    const filename = `avatars/${path.basename(req.file.path)}`;
    
    // 更新数据库
    await pool.query(
      'UPDATE users SET avatar = ? WHERE id = ?',
      [filename, userId]
    );

    res.json({
      success: true,
      avatar: filename
    });
  } catch (error) {
    console.error('Error uploading avatar:', error);
    res.status(500).json({ message: '上传头像失败' });
  }
});

// 更新密码
app.put('/api/user/password', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { oldPassword, newPassword } = req.body;
    
    // 验证数据
    if (!oldPassword || !newPassword) {
      throw new Error('原密码和新密码不能为空');
    }
    
    if (oldPassword === newPassword) {
      throw new Error('新密码不能与原密码相同');
    }
    
    // 更新密码
    await User.updatePassword(userId, oldPassword, newPassword);
    
    res.json({ message: '密码更新成功' });
  } catch (error) {
    console.error('Error in update password:', error);
    res.status(400).json({ message: error.message });
  }
});

// 确保上传目录存在
const ensureUploadDirs = () => {
  const dirs = [
    path.join(__dirname, '../../uploads'),
    path.join(__dirname, '../../uploads/products'), // 确保产品图片目录存在
    path.join(__dirname, '../../uploads/avatars'),
    path.join(__dirname, '../../uploads/banners')
  ];

  dirs.forEach(dir => {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
      console.log(`Created directory: ${dir}`);
    }
  });

  // 复制默认图片
  const defaultProductImage = path.join(__dirname, '../../uploads/products/default.png');
  if (!fs.existsSync(defaultProductImage)) {
    fs.copyFileSync(
      path.join(__dirname, '../assets/default-product.png'),
      defaultProductImage
    );
    console.log('Copied default product image');
  }
};

// 在应用启动时调用
ensureUploadDirs();

// 获取浏览记录
app.get('/api/user/recent-views', authenticateToken, async (req, res) => {
  try {
    const recentViews = await User.getRecentViews(req.user.id);
    res.json(recentViews);
  } catch (error) {
    console.error('Error in GET /api/user/recent-views:', error);
    res.status(500).json({ message: '获取浏览记录失败' });
  }
});

// 添加浏览记录
app.post('/api/user/recent-views/:productId', authenticateToken, async (req, res) => {
  try {
    await User.addRecentView(req.user.id, req.params.productId);
    res.json({ message: '添加成功' });
  } catch (error) {
    console.error('Error in POST /api/user/recent-views:', error);
    res.status(500).json({ message: '添加失败' });
  }
});

// 获取地址列表
app.get('/api/addresses', authenticateToken, async (req, res) => {
  try {
    const addresses = await Address.getAddresses(req.user.id);
    res.json(addresses);
  } catch (error) {
    console.error('Error in GET /api/addresses:', error);
    res.status(500).json({ message: '获取地址列表失败' });
  }
});

// 添加地址
app.post('/api/addresses', authenticateToken, async (req, res) => {
  try {
    const addressId = await Address.addAddress(req.user.id, req.body);
    res.json({ id: addressId });
  } catch (error) {
    console.error('Error in POST /api/addresses:', error);
    res.status(500).json({ message: '添加地址失败' });
  }
});

// 更新地址
app.put('/api/addresses/:id', authenticateToken, async (req, res) => {
  try {
    const success = await Address.updateAddress(req.user.id, req.params.id, req.body);
    if (success) {
      res.json({ message: '更新成功' });
    } else {
      res.status(404).json({ message: '地址不存在' });
    }
  } catch (error) {
    console.error('Error in PUT /api/addresses:', error);
    res.status(500).json({ message: '更新地址失败' });
  }
});

// 删除地址
app.delete('/api/addresses/:id', authenticateToken, async (req, res) => {
  try {
    const success = await Address.deleteAddress(req.user.id, req.params.id);
    if (success) {
      res.json({ message: '删除成功' });
    } else {
      res.status(404).json({ message: '地址不存在' });
    }
  } catch (error) {
    console.error('Error in DELETE /api/addresses:', error);
    res.status(500).json({ message: '删除地址失败' });
  }
});

// 在更新产品后清除缓存
app.put('/api/products/:id', authenticateToken, async (req, res) => {
  try {
    await Product.updateProduct(req.params.id, req.body);
    Product.clearCache('hot_products'); // 清除热门产品缓存
    res.json({ message: '更新成功' });
  } catch (error) {
    console.error('Error updating product:', error);
    res.status(500).json({ message: '更新失败' });
  }
});

// 获取轮播图
app.get('/api/banners', async (req, res) => {
  try {
    const banners = await Product.getBanners();
    res.json(banners);
  } catch (error) {
    console.error('Error fetching banners:', error);
    res.status(500).json({ 
      message: '获取轮播图失败',
      data: []
    });
  }
});

// AI聊天接口
app.post('/api/chat', authenticateToken, async (req, res) => {
  try {
    const { message } = req.body;
    const userId = req.user.id;

    console.log('Chat request received:', { userId, message });

    const result = await aiService.chat(message, userId);
    res.json(result);
  } catch (error) {
    console.error('Chat API error:', error);
    res.status(500).json({
      success: false,
      message: '聊天服务暂时不可用'
    });
  }
});

// 获取聊天历史
app.get('/api/chat/history', authenticateToken, async (req, res) => {
  try {
    // 使用 aiService 实例而不是 AIService 类
    const history = await aiService.getChatHistory(req.user.id);
    res.json({
      success: true,
      data: history
    });
  } catch (error) {
    console.error('Error fetching chat history:', error);
    res.status(500).json({
      success: false,
      message: '获取聊天历史失败'
    });
  }
});

// 获取商品推荐
app.get('/api/recommendations', authenticateToken, async (req, res) => {
  try {
    const userBehavior = {
      viewHistory: req.query.viewHistory?.split(',') || [],
      purchaseHistory: req.query.purchaseHistory?.split(',') || [],
      favorites: req.query.favorites?.split(',') || []
    }

    const result = await aiService.getProductRecommendations(
      req.user.id,
      userBehavior
    )

    res.json(result)
  } catch (error) {
    console.error('Error getting recommendations:', error)
    res.status(500).json({
      success: false,
      message: '获取推荐失败'
    })
  }
})

// 导入路由
app.use('/api/debug', debugRoutes);
app.use('/api/ai', aiRoutes);
app.use('/api/cart', cartRoutes);
app.use('/api/addresses', addressRoutes);
app.use('/api/orders', orderRouter);
app.use('/api/payments', paymentRouter);
app.use('/api/story', storyRoutes);
app.use('/api/user', userRoutes);
app.use('/api/admin', adminRoutes);

// 在所有路由之后添加错误处理中间件
app.use(function(err, req, res, next) {
  console.error('Server Error:', err);
  console.error('Error Stack:', err.stack);
  
  res.status(err.status || 500).json({
    success: false,
    message: process.env.NODE_ENV === 'production' 
      ? '服务器内部错误' 
      : err.message,
    error: process.env.NODE_ENV === 'production' ? {} : err
  });
});

// 404 处理 - 确保这是最后设置的中间件
app.use((req, res) => {
  console.log('404 Not Found:', req.url);
  res.status(404).json({ message: '接口不存在' });
});

// 启动服务器
const PORT = process.env.PORT || 5000;
app.listen(PORT, async () => {
  console.log(`Server is running on port ${PORT}`);
  console.log(`API文档地址: http://localhost:${PORT}/api-docs`);
  await testEmailConnection();
}); 